package com.ahstu.learning.ui;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ahstu.learning.R;
import com.ahstu.learning.base.BaseActivity;
import com.ahstu.learning.bean.User;
import com.ahstu.learning.event.ChatEvent;
import com.ahstu.learning.friend.FriendFragement;
import com.ahstu.learning.learning.LearningFragement;
import com.ahstu.learning.leftMenu.AboutActivity;
import com.ahstu.learning.leftMenu.TranslationActivity;
import com.ahstu.learning.model.UserModel;
import com.ahstu.learning.test.TestFragment;
import com.ahstu.learning.turing.MuToActivity;
import com.ahstu.learning.ui.fragment.ConversationFragment;
import com.ahstu.learning.util.IMMLeaks;
import com.nineoldandroids.view.ViewHelper;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.Subscribe;

import butterknife.Bind;
import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.newim.event.MessageEvent;
import cn.bmob.newim.event.OfflineMessageEvent;
import cn.bmob.newim.listener.ConnectListener;
import cn.bmob.newim.listener.ConversationListener;
import cn.bmob.newim.listener.ObseverListener;
import cn.bmob.newim.notification.BmobNotificationManager;
import cn.bmob.v3.exception.BmobException;

public class MainActivity extends BaseActivity implements ObseverListener {

    @Bind(R.id.btn_learning)
    Button btn_learning;
    @Bind(R.id.btn_test)
    Button btn_test;
    @Bind(R.id.btn_friend)
    Button btn_friend;
    @Bind(R.id.btn_conversation)
    Button btn_conversation;
    @Bind(R.id.iv_conversation_tips)
    ImageView iv_conversation_tips;

    //侧滑操作
    @Bind(R.id.btn_logout)
    Button btn_logout;
    @Bind(R.id.tv_left)
    TextView tv_left;


    private Button[] mTabs;
    private LearningFragement learningFragement;
    private TestFragment testFragment;
    private FriendFragement friendFragement;
    private ConversationFragment conversationFragment;
    private Fragment[] fragments;
    private int index;
    private int currentTabIndex;

    private LinearLayout leftmenutuling;
    private LinearLayout left_menuguanyu1;
    private LinearLayout translation;
    private long exitTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        translation = (LinearLayout) findViewById(R.id.translation);
        translation.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Intent intent = new Intent(MainActivity.this, TranslationActivity.class);
                startActivity(intent);
            }
        });
        leftmenutuling = (LinearLayout) findViewById(R.id.leftmenutuling1);
        leftmenutuling.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Intent intent = new Intent(MainActivity.this, MuToActivity.class);
                startActivity(intent);
            }
        });
        left_menuguanyu1 = (LinearLayout) findViewById(R.id.leftmenutuling2);
        left_menuguanyu1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(MainActivity.this, AboutActivity.class);
                startActivity(intent);
            }
        });
        //左侧用户名
        SharedPreferences sp = getSharedPreferences("name", MODE_PRIVATE);
        String username = sp.getString("username", "error");
        tv_left.setText(username);

        //连接服务器
        final User user = UserModel.getInstance().getCurrentUser();
        BmobIM.connect(user.getObjectId(), new ConnectListener() {
            @Override
            public void done(String uid, BmobException e) {
                if (e == null) {
                    // tv_left.setText(user.getUsername());
                } else {
                    Logger.e(e.getMessage());
                }
            }
        });
        //解决leancanary提示InputMethodManager内存泄露的问题
        IMMLeaks.fixFocusedViewLeak(getApplication());


        final DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerlaout);
        mDrawerLayout.setDrawerListener(new DrawerListener() {

            @Override
            public void onDrawerClosed(final View arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onDrawerOpened(final View arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onDrawerSlide(final View drawerView, final float arg1) {
                final View contentView = mDrawerLayout.getChildAt(0);
                // arg1表示菜单项滑出来的比例，打开菜单时取值为0->1,关闭菜单时取值为1->0
                final float scale = 1 - arg1;
                final float rightScale = 0.8f + scale * 0.2f;
                final float leftScale = 1 - 0.3f * scale;

                // 左边的动画
                ViewHelper.setScaleX(drawerView, leftScale);
                ViewHelper.setScaleY(drawerView, leftScale);
                ViewHelper.setAlpha(drawerView, 0.6f + 0.4f * (1 - scale));
                ViewHelper.setTranslationX(contentView, drawerView.getMeasuredWidth() * (1 - scale));

                // 右边的动画
                // ViewHelper.setPivotX(contentView, 0);
                // ViewHelper.setPivotY(contentView,
                // contentView.getMeasuredHeight() / 2);
                // contentView.invalidate();
                // ViewHelper.setScaleX(contentView, rightScale);
                // ViewHelper.setScaleY(contentView, rightScale);
            }

            @Override
            public void onDrawerStateChanged(final int arg0) {
                // TODO Auto-generated method stub

            }

        });

        //侧滑退出按钮
        btn_logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                User user = UserModel.getInstance().getCurrentUser();
//                toast(user+">>");
                UserModel.getInstance().logout();
                SharedPreferences sp = getSharedPreferences("name", MODE_PRIVATE);
                sp.edit().clear().commit();
                //可断开连接
                BmobIM.getInstance().disConnect();
                finish();
                startActivity(new Intent(MainActivity.this, LoginActivity.class));

            }
        });

    }

    @Override
    protected void initView() {
        super.initView();
        mTabs = new Button[4];
        mTabs[0] = btn_learning;
        mTabs[1] = btn_test;
        mTabs[2] = btn_friend;
        mTabs[3] = btn_conversation;
        mTabs[0].setSelected(true);
        initTab();
    }

    private void initTab() {
        learningFragement = new LearningFragement();
        testFragment = new TestFragment();
        friendFragement = new FriendFragement();
        conversationFragment = new ConversationFragment();
        fragments = new Fragment[]{learningFragement, testFragment, friendFragement, conversationFragment};
        getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, conversationFragment).
                add(R.id.fragment_container, testFragment).
                add(R.id.fragment_container, friendFragement).
                add(R.id.fragment_container, learningFragement).
                hide(testFragment).
                hide(friendFragement).
                hide(conversationFragment).
                show(learningFragement).commit();
    }

    public void onTabSelect(View view) {
        switch (view.getId()) {
            case R.id.btn_learning:
                index = 0;
                break;
            case R.id.btn_test:
                index = 1;
                break;
            case R.id.btn_friend:
                index = 2;
                break;
            case R.id.btn_conversation:
                index = 3;
                break;
        }
        onTabIndex(index);
    }

    private void onTabIndex(int index) {
        if (currentTabIndex != index) {
            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
            trx.hide(fragments[currentTabIndex]);
            if (!fragments[index].isAdded()) {
                trx.add(R.id.fragment_container, fragments[index]);
            }
            trx.show(fragments[index]).commit();
        }
        mTabs[currentTabIndex].setSelected(false);
        mTabs[index].setSelected(true);
        currentTabIndex = index;
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkRedPoint();
        //添加观察者-用于是否显示通知消息
        BmobNotificationManager.getInstance(this).addObserver(this);
        //进入应用后，通知栏应取消
        BmobNotificationManager.getInstance(this).cancelNotification();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //移除观察者
        BmobNotificationManager.getInstance(this).removeObserver(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //清理导致内存泄露的资源
        BmobIM.getInstance().clear();
        //完全退出应用时需调用clearObserver来清除观察者
        BmobNotificationManager.getInstance(this).clearObserver();
    }

    /**
     * 注册消息接收事件
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(MessageEvent event) {
        checkRedPoint();
    }

    /**
     * 注册离线消息接收事件
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(OfflineMessageEvent event) {
        checkRedPoint();
    }

    private void checkRedPoint() {
        if (BmobIM.getInstance().getAllUnReadCount() > 0) {
            iv_conversation_tips.setVisibility(View.VISIBLE);
        } else {
            iv_conversation_tips.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, SplashActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //响应FriendFragement中的list点击
    @Subscribe
    public void onEventMainThread(ChatEvent event) {
        BmobIMUserInfo info = event.info;
        //如果需要更新用户资料，开发者只需要传新的info进去就可以了
        Logger.i("" + info.getName() + "," + info.getAvatar() + "," + info.getUserId());
        BmobIM.getInstance().startPrivateConversation(info, new ConversationListener() {
            @Override
            public void done(BmobIMConversation c, BmobException e) {
                if (e == null) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("c", c);
                    startActivity(ChatActivity.class, bundle, false);
                } else {
                    toast(e.getMessage() + "(" + e.getErrorCode() + ")");
                }
            }
        });
    }
}
